// app.js
for (var i = 0; i < 4; i++) {
  setTimeout(function() {
    console.log(i);
  },100);
}

let oldPage = Page
let pages = [] //待登录后执行的页面
Page = function(args){
  //缓存onLoad
 let onLoad = args.onLoad
 //构造新的onload
 args.onLoad = function(options){
   ///拦截登录前的页面onLoad事件
   if(wx.userInfo && wx.token){//已登录，直接执行原来的onload事件
           onLoad.call(this,options)
   }else{//添加待执行页面缓存
    pages.push({
      context:this,//页面实列thisl
      onLoad,//原onLoad函数
      options//页面参数
      })     
   }
 }
  oldPage(args)
}



const { formatTime } = require('./utils/util')
let util = require('/utils/util.js')
console.log(util,formatTime(new Date()))

wx.$https = require('/utils/request')

let $https = require('/utils/request')
wx.$https = $https
wx.get = $https.get
wx.put = $https.put
wx.post = $https.post
wx.delete = $https.delete

App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)

    // 登录
    wx.login({
      success: res => {
        wx.get('http://localhost:3000/wxlogin?code='+res.code).then((res)=>{
                console.log(res)
                wx.userInfo = res
                wx.token = res.token
                if(pages.length){
                  for(let i = 0 ;i < pages.length ; i++){
                    let page = pages[i]
                    page.onLoad.call(page.context,page.options)
                  }
                }
        })
        // 发送 res.code 到后台换取 openId, sessionKey, unionId
      }
    })
  },
  globalData: {
    userInfo: null
  }
})
